<?php

namespace app\advertisement\logic;

use app\advertisement\model\Advaccountlog as AdvaccountlogModel;
use think\facade\Db;
use app\data\util\HttpUtil;
use ba\Exception;
use think\facade\Cache;
use app\common\library\Excel;
use Throwable;

class AdvaccountlogLogic
{
    protected $model = null;

    public function __construct()
    {
        $this->model = new AdvaccountlogModel();
    }
    /**
     * @param $params
     * @return \think\response\Json
     * @throws \think\db\exception\DbException
     * @desc 列表
     * @author zhangheng
     */
    public function index($params = [])
    {
        $advertiser_id = $params['advertiser_id'] ?? [];
        $admin_id = $params['admin_id'] ?? [];
        $shop_id = $params['shop_id'] ?? '';
        $limit = $params['limit'] ?? 10;
        $where = [];

        if(!empty($admin_id)){
            $where['a.admin_id'] = $admin_id;
        }
        if(!empty($shop_id)){
            $where['a.shop_id'] = $shop_id;
        }
        if(!empty($advertiser_id)){
            $where['d.advertiser_id'] = $advertiser_id;
        }
        $list = $this->model
            ->field('a.id,d.advertiser_id,a.shop_id,c.nickname as admin_title,a.createtime,a.updatetime,a.status')
            ->alias('a')
            ->join('ba_admin c','c.id = a.admin_id', 'left')
            ->join('ba_advaccount d','d.id = a.advertiser_id', 'left')
            ->where($where)
            ->order("a.updatetime desc")
            ->paginate($limit);

        $lists = $list->items();
        $shop_ids = array_column($lists,'shop_id');
        //批量获取店铺信息及sku数量信息;
        $shopInfos     = Db::name('shops')->whereIn('id',$shop_ids)->field('name,id')->select();
        $shopInfos     = objectToArray($shopInfos);
        $shopInfos_map = array_column($shopInfos,null,'id');

        foreach ($lists as $k=>$v) {
            $shop_names = $shopInfos_map[$v['shop_id']]??[];
            $lists[$k]['shop_name']     =  $shop_names['name']??'';
            if(!empty($v['createtime'])){
                $lists[$k]['createtime'] = date('Y-m-d', $v['createtime']);
            }
            if(!empty($v['updatetime'])){
                $lists[$k]['updatetime'] = date('Y-m-d', $v['updatetime']);
            }else{
                $lists[$k]['updatetime'] = "至今";
            }
        }

        $data = [
            'list' => $lists,
            'total' => $list->total(),
        ];
        return json(DefaultResponse(200, true, '获取成功', $data));
    }
    

    public function add($data)
    {
        if (!$data) {
            return json(DefaultResponse(201, false, '参数不能为空!', null));
        }

        $result = false;
        $this->model->startTrans();
        // try {
            //处理时间
            $data['createtime'] = strtotime($data['createtime']);
            if (empty($data['updatetime'])) {
                $data['updatetime'] = "";
            } else {
                $data['updatetime'] = strtotime($data['updatetime']);
            }

            //TODO
            //添加时保证当前只有唯一运营归属
            Db::name('advaccount_admin')
                ->where('status','normal')
                ->find();
            
            $result = $this->model->insert($data);
            
            $this->model->commit();
        // } catch (Throwable $e) {
        //     $this->model->rollback();
        //     return json(DefaultResponse(201, false, $e->getMessage(), null));
        // }
        if ($result !== false) {
            return json(DefaultResponse(200, true, '添加成功!', null));
        } else {
            return json(DefaultResponse(201, false, '添加失败!', null));
        }
    }

    public function edit($project, $data)
    {
        if (!$data) {
            return json(DefaultResponse(201, false, '参数不能为空!', null));
        }

        $result = false;
        $this->model->startTrans();
        try {
            //处理时间
            $data['createtime'] = strtotime($data['createtime']);
            if (empty($data['updatetime'])) {
                $data['updatetime'] = "";
            } else {
                $data['updatetime'] = strtotime($data['updatetime']);
                //如果有值 状态改成停用
                $data['status'] = "hidden";
            }

            $result = $project->save($data);
            $this->model->commit();
        } catch (Throwable $e) {
            $this->model->rollback();
            return json(DefaultResponse(201, false, $e->getMessage(), null));
        }
        if ($result !== false) {
            return json(DefaultResponse(200, true, '更新成功!', null));
        } else {
            return json(DefaultResponse(201, false, '更新失败!', null));
        }
    }
    
}
